package com.example.basesystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.basesystem.entity.SysRoleMenu;
import com.example.basesystem.entity.SysUser;
import com.example.basesystem.entity.SysUserRole;
import com.example.basesystem.mapper.SysUserMapper;
import com.example.basesystem.mapper.SysUserRoleMapper;
import com.example.basesystem.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户服务实现类
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Page<SysUser> getUserPage(Page<SysUser> page, String username, Integer status) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .like(StringUtils.hasText(username), SysUser::getUsername, username)
                .eq(status != null, SysUser::getStatus, status)
                .orderByAsc(SysUser::getId);
        Page<SysUser> userPage = page(page, queryWrapper);
        //去除密码
        userPage.getRecords().forEach(user -> user.setPassword(null));
        return userPage;
    }

    @Override
    public SysUser getUserByUsername(String username) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, username);
        return getOne(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addUser(SysUser user, List<Long> roleIds) {
        // 设置默认值
        user.setCreateTime(LocalDateTime.now());
        user.setStatus(1);
        user.setIsDeleted(0);
        
        // 密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        
        // 保存用户
        boolean result = save(user);
        
        // 保存用户角色关联
        if (result && roleIds != null && !roleIds.isEmpty()) {
            assignUserRole(user.getId(), roleIds);
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUser(SysUser user, List<Long> roleIds) {
        // 设置更新时间
        user.setUpdateTime(LocalDateTime.now());
        
        // 如果密码不为空，则加密
        if (StringUtils.hasText(user.getPassword())) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        } else {
            // 不更新密码
            user.setPassword(null);
        }
        
        // 更新用户
        boolean result = updateById(user);
        
        // 更新用户角色关联
        if (result && roleIds != null) {
            assignUserRole(user.getId(), roleIds);
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUser(Long userId) {
        // 删除用户角色关联
        sysUserRoleMapper.deleteByUserId(userId);
        
        // 删除用户
        return removeById(userId);
    }

    @Override
    public boolean resetPassword(Long userId, String password) {
        SysUser user = new SysUser();
        user.setId(userId);
        user.setPassword(passwordEncoder.encode(password));
        user.setUpdateTime(LocalDateTime.now());
        return updateById(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean assignUserRole(Long userId, List<Long> roleIds) {
        // 删除原有用户角色关联
        sysUserRoleMapper.deleteByUserId(userId);
        
        // 添加新的用户角色关联
        List<SysUserRole> userRoleList = new ArrayList<>();
        for (Long roleId : roleIds) {
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            userRole.setCreateTime(LocalDateTime.now());
            userRoleList.add(userRole);
        }

        // 批量插入
        if (!userRoleList.isEmpty()) {
            // 批量插入角色菜单关联
            for (SysUserRole roleMenu : userRoleList) {
                sysUserRoleMapper.insert(roleMenu);
            }
            return true;
        }
        
        return true;
    }
}